//
//  ListViewController.m
//  JXPagerViewExample-OC
//
//  Created by jiaxin on 2019/12/30.
//  Copyright © 2019 jiaxin. All rights reserved.
//

#import "LessonStudyItemViewController.h"
#import "LessonCenterViewController.h"
#import "VideoPlayerViewController.h"
#import "ExercisesPageViewController.h"
#import "LessonDetailViewController.h"
#import "ExercisesAnswerResultViewController.h"

#import "LessonStudyItemCell.h"
#import "LessonStudyNoDataCell.h"
#import "LessonPlanModel.h"
#import "LessonPageItemModel.h"
@interface LessonStudyItemViewController () <UITableViewDataSource, UITableViewDelegate,LessonStudyNoDataCellDelegate,LessonStudyItemCellDelegate>
@property (nonatomic, copy) void(^scrollCallback)(UIScrollView *scrollView);
@property (nonatomic,copy)NSString *subjectId;
@property (nonatomic,strong)NSMutableArray *sourceArray;
@property (nonatomic,strong)NSMutableArray *alreadyArray;
@property (nonatomic,strong)NSMutableArray *prepareArray;
@property (nonatomic,assign)BOOL loading;
@property (nonatomic,assign)BOOL status;
@property (nonatomic,strong)LessonPlanModel *currentModel;


@property (nonatomic,strong)NSMutableArray *paperArray;

@end

@implementation LessonStudyItemViewController

- (NSMutableArray *)paperArray{
    if (!_paperArray) {
        _paperArray = [NSMutableArray array];
    }
    return _paperArray;
}

- (NSMutableArray *)alreadyArray{
    if (!_alreadyArray) {
        _alreadyArray = [NSMutableArray array];
    }
    return _alreadyArray;
}
- (NSMutableArray *)prepareArray{
    if (!_prepareArray) {
        _prepareArray = [NSMutableArray array];
    }
    return _prepareArray;
}
- (NSMutableArray *)sourceArray{
    if (!_sourceArray) {
        _sourceArray = [NSMutableArray array];
    }
    return _sourceArray;
}

- (instancetype)initWithSubjectId:(NSString *)subjectId status:(BOOL)status{
    if (self = [super init]) {
        self.subjectId = subjectId;
        self.status = status;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.isHideNavBar = YES;
    self.view.backgroundColor = RGBA(248, 248, 248, 1);
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(8, 0, kScreenW - 24, kScreenH - kNavBarHeight - 90) style:UITableViewStyleGrouped];
//    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = RGBA(248, 248, 248, 1);
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.estimatedRowHeight = 100;
    self.tableView.estimatedSectionFooterHeight = .0f;
    self.tableView.estimatedSectionHeaderHeight = .0f;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    //列表的contentInsetAdjustmentBehavior失效，需要自己设置底部inset
    [self.view addSubview:self.tableView];
           
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.cl_height = 138.0f;
    self.tableView.mj_footer = footer;
    
    self.tableView.mj_footer.hidden = YES;
    
    [self loadRequest];
}

- (void)refreshData{
    [self loadRequest];
}

- (void)loadRequest{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"id"] = [RPAppManager getCustomerId];
    if ([self.subjectId isEqualToString:@"0"]) {
        param[@"pageSize"] = @(9999);
        param[@"pageIndex"] = @(1);
        param[@"md5"] = [RPAppManager md5StrWithApi:GetUserPlanList];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUserPlanList) parames:param success:^(id responseObj) {
            self.loading = YES;
            if (![responseObj[RESPONSE] isKindOfClass:[NSNull class]]) {
                self.sourceArray = [LessonPlanModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][@"list"]];
            }else{
                [self.sourceArray removeAllObjects];
            }
            [self updateDateSourceWithStatus:self.status];
            [self hideDataLoadLoadState];
        } failure:^(NSError *error) {
            [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
            [self hideDataLoadLoadState];
        }];
    }else{
        param[@"subjectId"] = [NSNumber numberWithInt:(self.subjectId.intValue + 1)];
        param[@"md5"] = [RPAppManager md5StrWithApi:GetUserPlanListBySubject];
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetUserPlanListBySubject) parames:param success:^(id responseObj) {
            self.sourceArray = [LessonPlanModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
            self.loading = YES;
            [self updateDateSourceWithStatus:self.status];
            [self hideDataLoadLoadState];
        } failure:^(NSError *error) {
            [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
            [self hideDataLoadLoadState];
        }];
    }
}

- (void)removeUserPlanList{
    [MobClick event:@"lesson_delete_click"];
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定移除此课程？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [alertController dismissViewControllerAnimated:YES completion:nil];
    }];

    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];

        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        
        param[@"md5"] = [RPAppManager md5StrWithApi:DelUserPlanList];
        param[@"userId"] = [RPAppManager getCustomerId];
        param[@"lessonId"] = self.currentModel.id;
        [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(DelUserPlanList) parames:param success:^(id responseObj) {
            
            [WHToast showImage:[UIImage imageNamed:@"toast_tag_success"] message:@"移除成功" duration:2 finishHandler:nil];
            
            NSInteger index = -1;
            if (self.status) {
                index = [self.alreadyArray indexOfObject:self.currentModel];
                [self.alreadyArray removeObject:self.currentModel];
                self.tableView.mj_footer.hidden = self.alreadyArray.count == 0;
            }else{
                index = [self.prepareArray indexOfObject:self.currentModel];
                [self.prepareArray removeObject:self.currentModel];
                self.tableView.mj_footer.hidden = self.prepareArray.count == 0;
            }
            
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            
        
            if (self.status) {
                self.alreadyArray.count == 0?[self.tableView reloadData]:[self.tableView deleteSection:index withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                self.prepareArray.count == 0?[self.tableView reloadData]:[self.tableView deleteSection:index withRowAnimation:UITableViewRowAnimationAutomatic];
            }
            
            [RPAppManager deleteUserPlanById:self.currentModel.id.stringValue];
            // 刷新
           
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateStudyList" object:nil];

            
        } failure:^(id error) {
        
        }];
    }];
    [confirmAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
    [cancelAction setValue:[RPAppManager themColor] forKey:@"titleTextColor"];
             //往alertViewController上添加alertAction
    [alertController addAction:cancelAction];
    [alertController addAction:confirmAction];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];

    
}

- (void)updateDateSourceWithStatus:(BOOL)status{
    self.status = status;
    [self.alreadyArray removeAllObjects];
    [self.prepareArray removeAllObjects];
    [self.paperArray removeAllObjects];

    [self.sourceArray enumerateObjectsUsingBlock:^(LessonPlanModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.progress.intValue == 10000 && obj.paperAnswerId.intValue != 0) {
            [self.alreadyArray addObject:obj];
        }else{
            ExercisesPageModel *itemModel = [ExercisesPageModel getCurrentExercieseById:obj.paperId];
            if (itemModel != nil) {
                [self.paperArray addObject:itemModel];
            }else{
                ExercisesPageModel *newModel = [ExercisesPageModel new];
                [self.paperArray addObject:newModel];
            }
            [self.prepareArray addObject:obj];
        }
    }];
        
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
    
    self.tableView.mj_footer.hidden = self.status?self.alreadyArray.count == 0:self.prepareArray.count == 0;
    
    [self.tableView reloadData];
}

#pragma mark - UITableViewDataSource, UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    int maxCount = self.loading?0:-1;
    if (self.status) {
        return self.alreadyArray.count == 0?1+maxCount:self.alreadyArray.count;
    }else{
        return self.prepareArray.count == 0?1+maxCount:self.prepareArray.count;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.status) {
        // 判断是否有数据
        if (self.alreadyArray.count == 0) {
            LessonStudyNoDataCell *cell =  [LessonStudyNoDataCell cellWithTableView:tableView];
            cell.delegate = self;
            [cell setNoMessage:@"还没有已学完的课程哦～" stauts:YES];
            return cell;
        }
        LessonStudyItemCell *cell = [LessonStudyItemCell cellWithTableView:tableView];
        cell.delegate = self;
        [cell setPlanModel:self.alreadyArray[indexPath.section] andPaperModel:[ExercisesPageModel new]];
       
        return cell;
    }else{
        // 判断是否有数据
        if (self.prepareArray.count == 0) {
            LessonStudyNoDataCell *cell =  [LessonStudyNoDataCell cellWithTableView:tableView];
            cell.delegate = self;
            [cell setNoMessage:@"还没有课程哦～" stauts:NO];
           
            return cell;
        }
        LessonStudyItemCell *cell = [LessonStudyItemCell cellWithTableView:tableView];
        cell.delegate = self;
        [cell setPlanModel:self.prepareArray[indexPath.section] andPaperModel:self.paperArray[indexPath.section]];
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 16.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}


- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:(UITableViewRowActionStyleDefault) title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        if (self.status) {
            self.currentModel = self.alreadyArray[indexPath.section];
        }else{
            self.currentModel = self.prepareArray[indexPath.section];}
        
        [self removeUserPlanList];
    }];
     
    if (self.status) {
        return self.alreadyArray.count == 0?@[]:@[deleteAction];
    }else{
        return self.prepareArray.count == 0?@[]:@[deleteAction];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    !self.scrollCallback ?: self.scrollCallback(scrollView);
}
#pragma mark - CourseStudyNoDataCellDelegateDelegate
- (void)choiceCourseStudy{
    LessonCenterViewController *centerVC = [[LessonCenterViewController alloc]initWithSeachArray:self.searchArray andCurrentIndex:self.subjectId.intValue == 0?1:self.subjectId.integerValue];
    [self.navigationController pushViewController:centerVC animated:YES];
}

#pragma mark - CourseStudyItemCellDelegate
- (void)didSelectedAtCurrentModel:(LessonPlanModel *)model{
    [self showDataLoadState];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = model.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetH5LessonDetail];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetH5LessonDetail) parames:param success:^(id responseObj) {
        NSMutableArray *arr = [NSMutableArray array];
        LessonPageItemModel *itemModel = [[LessonPageItemModel alloc]init];
        itemModel.id = model.id;
        itemModel.title = model.title;
        itemModel.videoUrl = model.videoUrl;
        itemModel.videoId = model.videoId.stringValue;
        itemModel.paperAnswerId = model.paperAnswerId;
        itemModel.isSeleted = YES;
        itemModel.paperId = model.paperId;
        itemModel.isAnswerd = model.paperAnswerId.intValue > 0;
        [arr addObject:itemModel];
        
        LessonDetailModel *dtlModel = [LessonDetailModel mj_objectWithKeyValues:responseObj[RESPONSE]];
        
        VideoPlayerViewController *video = [[VideoPlayerViewController alloc]init];
        video.lessonModel = dtlModel;
        video.items = arr;
        NavigationViewController *nav = [[NavigationViewController alloc]initWithRootViewController:video];
        [self presentViewController:nav animated:YES completion:nil];
        __weak typeof(self)weakSelf = self;
        video.updateVideoProgressWithCurentModel = ^(CGFloat currentTime, CGFloat totalTime, LessonPageItemModel * _Nonnull itemModel) {
            __strong typeof(weakSelf)strongSelf = weakSelf;
            CGFloat rounded_up2 = currentTime / totalTime;
            int value = (int)(floorf(rounded_up2 * 100 * 100));
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            param[@"userId"] = [RPAppManager getCustomerId];
            param[@"lessonId"] = itemModel.id;
            param[@"videoPlayedTime"] = @(value);
            param[@"md5"] = [RPAppManager md5StrWithApi:SaveUserVideoLog];
            [self showDataLoadState];
            [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(SaveUserVideoLog) parames:param success:^(id responseObj) {
                [strongSelf loadRequest];
            } failure:^(id error) {
                [strongSelf hideDataLoadLoadState];
            }];
        };
    } failure:^(NSError *error) {
        [self hideDataLoadLoadState];
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
    
}
- (void)startExercieseAtCurrentModel:(LessonPlanModel *)model{
    
    [self showDataLoadState];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = model.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetH5LessonDetail];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetH5LessonDetail) parames:param success:^(id responseObj) {
        [self hideDataLoadLoadState];
        if (model.paperAnswerId.intValue != 0) {
            ExercisesAnswerResultViewController *resultVC = [[ExercisesAnswerResultViewController alloc]init];
            resultVC.lessonId = model.id.stringValue;
            [self.navigationController pushViewController:resultVC animated:YES];
        }else{
            ExercisesPageViewController *pageVC = [[ExercisesPageViewController alloc]initWithLessonId:model.id paperId:model.paperId];
            [self.navigationController pushViewController:pageVC animated:YES];
        }
    } failure:^(NSError *error) {
        [self hideDataLoadLoadState];
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
    
    

}
- (void)showCourseDetailAtCurrentModel:(LessonPlanModel *)model{
    
    [self showDataLoadState];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"lessonId"] = model.id;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetH5LessonDetail];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetH5LessonDetail) parames:param success:^(id responseObj) {
        [self hideDataLoadLoadState];
        [MobClick event:@"lesson_show_total" attributes:@{@"enter":@"study_plan_lesson"}];
        LessonDetailViewController *dtlVC = [[LessonDetailViewController alloc]init];
        dtlVC.lessonId = model.id;
        [self.navigationController pushViewController:dtlVC animated:YES];
        dtlVC.updateCourseStatus = ^(NSNumber * _Nonnull lessonId) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"updateStudyList" object:nil];
        };
    } failure:^(NSError *error) {
        [self hideDataLoadLoadState];
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
    }];
}

#pragma mark - JXPagingViewListViewDelegate

- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.tableView;
}

- (void)listViewDidScrollCallback:(void (^)(UIScrollView *))callback {
    self.scrollCallback = callback;
}



@end
